﻿using System;
using Microsoft.SharePoint;
using InfoJetSoft.Service.Util;
using ServBus.ListForm2013.Utility;

namespace ServBus.ListForm2013.Extension
{
    public class InlineFileStorage : IInlineFileStorage
    {
        private string GetSizeString(long size)
        {
            if (size < 1024)
                return size.ToString() + "B";

            double dSize = 0;
            if (size < 1024 * 1024)
            {
                dSize = size / 1024.0;
                return dSize.ToString("F2") + "KB";
            }
            else if (size < 1024 * 1024 * 1024)
            {
                dSize = size / (1024.0 * 1024.0);
                return dSize.ToString("F2") + "MB";
            }
            else
            {
                dSize = size / (1024.0 * 1024.0 * 1024.0);
                return dSize.ToString("F2") + "GB";
            }
        }

        #region IInlineFileStorage 成员

        public string Cache(string fileName, byte[] fileContent)
        {
            string cache = null;
            SPSecurity.RunWithElevatedPrivileges(() =>
            {
                using (SPSite site = new SPSite(SPContext.Current.Site.ID))
                {
                    using (SPWeb web = site.OpenWeb(SPContext.Current.Web.ID))
                    {
                        web.AllowUnsafeUpdates = true;
                        Guid doclibId = new Guid(web.Properties[Constants.ATT_LIB_KEY]);
                        SPList xdocList = web.Lists[doclibId];
                        SPFolder folder = xdocList.RootFolder.SubFolders.Add(Convert.ToString(Guid.NewGuid()));
                        SPFile file = folder.Files.Add(fileName, fileContent, true);
                        cache = file.ServerRelativeUrl;
                    }
                }
            });

            return cache;
        }

        public byte[] Restore(string fileUrl)
        {
            SPWeb web = SPContext.Current.Web;
            SPFile file = web.GetFile(fileUrl);
            return file.OpenBinary();
        }
        public string GetSize(string fileUrl)
        {
            SPWeb web = SPContext.Current.Web;
            SPFile file = web.GetFile(fileUrl);
            return GetSizeString(file.Length);
        }
        public string GetName(string fileUrl)
        {
            return System.IO.Path.GetFileName(fileUrl);
        }

        #endregion
    }
}
